package blog.routing;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import constant.Constants;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // 1. 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 2. 设置参数
        factory.setHost(Constants.HOST); // ip 的默认值为 localhost
        factory.setPort(Constants.PORT); // 默认值为 5672
        factory.setVirtualHost(Constants.VIRTUAL_HOST); // 虚拟主机，默认值为 /
        // 账号
        factory.setUsername(Constants.USER_NAME); // 用户名，默认为 guest
        factory.setPassword(Constants.USER_PASSWORD); // 密码，默认为 guest
        // 3. 创建连接 Connection
        Connection connection = factory.newConnection(); // 需要处理异常，在此处直接抛出，并不进行处理
        // 4. 创建 Channel
        Channel channel = connection.createChannel();
        // 5. 声明交换机
        channel.exchangeDeclare(Constants.ROUTING_CHANGE, BuiltinExchangeType.DIRECT, true, false, false, null);
        // 6. 声明队列
        channel.queueDeclare(Constants.ROUTINT_QUEUE_1, true, false, false, null);
        channel.queueDeclare(Constants.ROUTINT_QUEUE_2, true, false, false, null);
        // 7. 绑定交换机和队列
        channel.queueBind(Constants.ROUTINT_QUEUE_1, Constants.ROUTING_CHANGE, "a", null);
        channel.queueBind(Constants.ROUTINT_QUEUE_2, Constants.ROUTING_CHANGE, "a", null);
        channel.queueBind(Constants.ROUTINT_QUEUE_2, Constants.ROUTING_CHANGE, "b", null);
        channel.queueBind(Constants.ROUTINT_QUEUE_2, Constants.ROUTING_CHANGE, "c", null);
        // 8. 发送消息
        String messageA = "test a...";
        channel.basicPublish(Constants.ROUTING_CHANGE, "a", null, messageA.getBytes());
        String messageB = "test b...";
        channel.basicPublish(Constants.ROUTING_CHANGE, "b", null, messageB.getBytes());
        String messageC = "test c... ";
        channel.basicPublish(Constants.ROUTING_CHANGE, "c", null, messageB.getBytes());
        System.out.println("消息发送成功!");
        // 9. 释放资源
        channel.close();
        connection.close();
    }
}
